require(['loading'], function(loading) {
	//获取url中的参数
	var params = getUrlParams();
	var first = params.first?params.first:'';
	if(first == 1){
		history.pushState({},"","");
		page = 3;
	}
	var page;
	window.onpopstate = function(event) {
		if(page == 2){
			window.location.href = self_base_path + '/farmManage/farmManage.html';
		}else if(page == 3){
			window.location.href = self_base_path + '/sales/sales_index.html';
		}else{
			var areaBottom = $("#areaLayer").css('bottom');
			if(areaBottom == '0px'){
				$('#areaLayer').animate({"bottom": "-100%"});
			} else {
				$('#addName,#address,#iphone,#areaLayer').animate({"bottom": "-100%"});
				$('#main').show();
			}
		}
	};
	
	//应用实例化
    var myFarm = new Vue({
        el: '#myFarm',
        data: {
            farmInfo: {},
            provinceData:[],
			cityData: [],
			countyData: [],
			isProv: false,
			isCity: false,
			isCout: false,
            showLoading: false,
            isImg: true,
            apiUrl: wxUrl + '/v3.3/farm/farmInfo',
            modifyUrl: wxUrl + '/v3.3/farm/updateFarmInfo',
            areaUrl: wxUrl + '/area/areaChildren',
            item: {
                params:{
                    token: token,
                    userToken: userToken
                }
            },
            modifyItem: {
                params:{
                    token: token,
                    userToken: userToken,
                    coverPic: '',
                    name: '',
                    telephone: '',
                    lng:'',
                    lat:'',
                    area:'',
                    address:''
                }
            },
            areaItem: {
				params:{
					token: token,
					userToken: userToken,
					parentId: ''
				}
			}
        },
        ready: function() {
        	this.getFarmInfo();
        },
        methods: {
            getFarmInfo: function() {
                this.$http.get(this.apiUrl, this.item)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        var farmInfo = result.data.farmInfo;
                        console.log(farmInfo)
                        if(farmInfo.coverPic == '' || farmInfo.coverPic == null){
                        	$('#file-list').hide();
                        }else{
                        	$('#cameraImg').hide();
                        	$('#file-list').show();
                        }
                        /*if(farmInfo.name == '' || farmInfo.name == null){
//                      	$("#name").text("请输入农庄名称");
                        	farmInfo.name = '请输入农庄名称';
                        }
                        
                        if(farmInfo.telephone == '' || farmInfo.telephone == null){
                        	farmInfo.telephone = '请输入联系电话';
                        }*/
                        if(farmInfo.area == '' || farmInfo.area == null || farmInfo.area == 0 || farmInfo.address == '' || farmInfo.address == null || farmInfo.address == 0){
                        	farmInfo.area = '';
                        	farmInfo.address = '';
                        }
                        this.$set('farmInfo', farmInfo);
						
                    },function(response) {
                        //errorCallback
                    });
            },
            clickModify: function (type) {
            	history.pushState({},"","");
            	page = 1;
            	$('#main').hide();
            	if(type == 1){
            		$('#addName').animate({"bottom": 0}); //名称
            	} else if(type == 2){
            		$('#address').animate({"bottom": 0}); //地址
            		baiduMap(); //调用百度地图
            	} else if(type == 3){
            		$('#iphone').animate({"bottom": 0});  //电话
            	} else if(type == 4){
            		$('#areaLayer').animate({"bottom": 0});  //三级联动
            		this.getProvince();
            	}
            },
            modifySubmit: function (e, type) {
            	if (type == 1) { //农庄名称
            		var farmName = $('#farmName').val();
            		if(farmName == null || farmName == undefined || farmName == "" || farmName.length<2){
            			promptBox('最少2个字！');
				        return;
				    }else{
				    	var reg = /^[a-zA-z0-9\u4E00-\u9FA5]*$/;
						if(!reg.test(farmName)){
							promptBox('不能含有特殊字符！');
				        	return;
						}
				    }
				    this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    coverPic: this.farmInfo.coverPic,
	                    name: farmName,
	                    telephone: this.farmInfo.telephone,
	                    lng: this.farmInfo.lng,
	                    lat: this.farmInfo.lat,
	                    area: this.farmInfo.area,
	                    address: this.farmInfo.address
	                };
            	} else if (type == 2) { //地址选择
            		var pcdAddress = $('#pcdAddress').val();
            		var detailAddress = $('#detailAddress').val();
            		if(pcdAddress == null || pcdAddress == undefined || pcdAddress == ""){
            			promptBox('所在区域不能为空');
				        return;
				    }
            		if(detailAddress == null || detailAddress == undefined || detailAddress == ""){
            			promptBox('详细地址不能为空');
				        return;
				    }
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    coverPic: this.farmInfo.coverPic,
	                    name: this.farmInfo.name,
	                    telephone: farmTel,
	                    lng: this.farmInfo.lng,
	                    lat: this.farmInfo.lat,
	                    area: pcdAddress,
	                    address: detailAddress
	                };
	            } else if (type == 3) { //联系电话
            		var farmTel = $('#farmTel').val().trim();
            		if(farmTel == null || farmTel == undefined || farmTel == ""){
            			promptBox('联系电话不能为空');
				        return;
				    }else{
				    	var tel1 = /^[1][34587]\d{9}$/; //手机号
				    	var tel2 =  /^0\d{2,3}\d{5,9}|0\d{2,3}\d{5,9}$/; //固定电话
			            if(!tel1.test(farmTel) && !tel2.test(farmTel)) {
			                promptBox("请输入正确的联系方式");
			                return;
			            }
				    }
            		this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    coverPic: this.farmInfo.coverPic,
	                    name: this.farmInfo.name,
	                    telephone: farmTel,
	                    lng: this.farmInfo.lng,
	                    lat: this.farmInfo.lat,
	                    area: this.farmInfo.area,
	                    address: this.farmInfo.address
	                };
	            }else if (type == 4) {
	            	this.modifyItem.params = {
            			token: token,
	                    userToken: userToken,
	                    coverPic: this.farmInfo.coverPic,
	                    name: this.farmInfo.name,
	                    telephone: this.farmInfo.telephone,
	                    lng: this.farmInfo.lng,
	                    lat: this.farmInfo.lat,
	                    area: this.farmInfo.area,
	                    address: this.farmInfo.address
	                };
	            }
            	this.$http.get(this.modifyUrl, this.modifyItem)
                    .then(function(response) {
                        var result = JSON.parse(response.body);
                        if(result.code == 0){
                        	page = 2;
                    		$('#addName,#address,#iphone').animate({"bottom": "-100%"});
							$('#main').show();
							this.getFarmInfo();
                        }
                        var nickName = $('#nickName').val();
                        var areaAddr = $('#areaAddr').val();
                        if(nickName.length > 1 && areaAddr.length > 1){
							promptBox('农庄信息已完善！');
						}
                    },function(response) {
                        //errorCallback
                    });
            },
            getProvince: function(){
				this.areaItem.params.parentId = '';
				this.isProv = true;
				this.isCity = false;
				this.isCout = false;
				$("#areaBox").scrollTop(0);
				expressArea = "";
				//获取省份
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('provinceData', result.data.areaList);
					},function(response) {
						//errorCallback
					});
			},
			getCity: function(e){
				this.areaItem.params.parentId = $(e.currentTarget).attr('id');
				$('.backCity').attr('id',$(e.currentTarget).attr('id'));
				this.isProv = false;
				this.isCity = true;
				this.isCout = false;
				expressArea += $(e.currentTarget).text() + ' ';
				$("#areaBox").scrollTop(0);
				//获取城市
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('cityData', result.data.areaList);
					},function(response) {
						//errorCallback
					});
			},
			getCounty: function(e){
				this.areaItem.params.parentId = $(e.currentTarget).attr('id');
				this.isProv = false;
				this.isCity = false;
				this.isCout = true;
				expressArea += $(e.currentTarget).text() + ' ';
				$("#areaBox").scrollTop(0);
				//获取县区
				this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response) {
						var result = JSON.parse(response.body);
						this.$set('countyData', result.data.areaList);
					},function(response) {
						//errorCallback
					});
			},
			overArea: function(e){
				this.isProv = false;
				this.isCity = false;
				this.isCout = false;
				$("#areaMask").fadeOut();
				$("#areaLayer").animate({"bottom": "-100%"});
				expressArea += $(e.currentTarget).text() + ' ';
				$("#pcdAddress").val(expressArea); //三级文字地址
				var dId = $(e.currentTarget).text();
				
				baiduMap().getPoint_s(expressArea);
			},
			closeArea: function(){
				$('#areaLayer').animate({"bottom": '-100%'});  //三级联动
			}
        }
    });

	//上传图片
	$('#myFarmImg').diyUpload({
		url: wxUrl + '/v3.3/personalInfo/upload',
		multiple: false,
		success:function(data){
			if(data.data.success){
				promptBox('上传成功！');
				myFarm.farmInfo.coverPic = data.data.url;
				myFarm.farmInfo.coverPicUrl = data.data.fullurl;
				console.log(myFarm.farmInfo.coverPicUrl)
				myFarm.modifySubmit(this,4);
			} else{
				promptBox('上传失败！');
			}
		},
		error:function(err){
			promptBox(err);
		}
	});
	
	//百度地图示例
	var baiduMap = (function(){
		var map = new BMap.Map("mapContainer");
		var geoc = new BMap.Geocoder();
		if(myFarm.farmInfo.lng != '' && myFarm.farmInfo.lng != null){
			longitude = myFarm.farmInfo.lng;
		}
		if(myFarm.farmInfo.lat != '' && myFarm.farmInfo.lat != null){
			latitude = myFarm.farmInfo.lat;
		}
		var point = new BMap.Point(longitude, latitude);
		map.centerAndZoom(point, 15);
		getLocation_s(point);//根据定位 初始化地址
		var marker = new BMap.Marker(map.getCenter());
		map.addEventListener("moveend",function(){
			if(marker){
				marker.setPosition(map.getCenter());
				getLocation_s(map.getCenter());
			}
		});
		map.addEventListener("zoomend",function(){
			if(marker){
				marker.setPosition(map.getCenter());
				map.panTo(new BMap.Point(longitude,latitude));
			}
		});
		function getLocation_s(pt){
			geoc.getLocation(pt, function(rs){
				var addComp = rs.addressComponents;
				province = addComp.province;
				city = addComp.city;
				district = addComp.district;
				street = addComp.street;
				streetNumber = addComp.streetNumber;
				myFarm.farmInfo.lng = pt.lng;
				myFarm.farmInfo.lat = pt.lat;
				var address = province + ' ' + city + ' ' + district;
				var detailAddress = street+streetNumber;
				$("#pcdAddress").val(address);
				$('#detailAddress').val(detailAddress);
				$('#detailAddress2').text(detailAddress);
			});
		};
		getPoint_s = function(adds){
			geoc.getPoint(adds, function(point){
				if (point) {
					map.centerAndZoom(point, 15);
					map.addOverlay(new BMap.Marker(point));
				}else{
					promptBox("您选择地址没有解析到结果!");
				}
			}, '北京市');
		};
		return{
			getPoint_s : getPoint_s
		};
	});
});